<template>
    <div id="login">
        <el-card>
            <template #header>
                <div>登录 侯佳俊</div>
            </template>
            <el-form label-width="60px">
                <el-form-item label="用户名">
                    <el-input v-model="form.username"></el-input>
                </el-form-item>
                <el-form-item label="密码">
                    <el-input v-model="form.password" type="password"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="loginLoading">
                        登录
                    </el-button>
                </el-form-item>
            </el-form>
        </el-card>
    </div>
</template>
<script>
import { mapActions } from "vuex"; // 导入助手函数
export default {
    data() {
        return {
            form: {
                username: "",
                password: "",
            },
        };
    },
    beforeRouteEnter(to, from, next) {
        next( (vm) => {
            if (localStorage.token) {
                vm.$router.push({
                    name: "UsersIndex",
                });
            }
        });
        
    },
    methods: {
        ...mapActions("users", ["login"]), // 将 users 模块下的 login 方法映射到当前组件的 methods 中
        async loginLoading(){
            try {
                const {data} = await this.login({
                    username:this.form.username,
                    password:this.form.password,
                });
                localStorage.token = data;
                this.$message.success('登录成功');
                this.$router.push({
                    name: "UsersIndex",
                });
            }catch (error) {
                // this.$message.error(error.response.data.message)
            }
        }
    },
};
</script>
<style lang="scss">
#login {
    .el-card {
        width: 400px;
        margin: 0 auto;
        margin-top: 100px;
    }
}
</style>